import { API_CONFIG, getSessionId } from './config.js';


// 本地缓存上传的文件
const cachedFiles = new Map();

// 上传文件到本地缓存
export const uploadFiles = async (files) => {
  console.log('uploadFiles 被调用, 文件:', files)

  try {
    const sessionId = getSessionId();
    console.log('sessionId:', sessionId)

    const newFiles = Array.from(files).map(file => ({
      name: file.name,
      size: file.size,
      type: file.type,
      lastModified: file.lastModified,
      file: file
    }));

    console.log('newFiles:', newFiles)

    // 获取现有缓存文件或创建新数组
    const existingFiles = cachedFiles.get(sessionId) || [];
    console.log('现有缓存文件:', existingFiles)

    // 合并文件，避免重复
    const mergedFiles = [...existingFiles];
    newFiles.forEach(newFile => {
      if (!existingFiles.some(f => f.name === newFile.name && f.lastModified === newFile.lastModified)) {
        mergedFiles.push(newFile);
      }
    });

    cachedFiles.set(sessionId, mergedFiles);
    console.log('当前缓存文件:', mergedFiles);
    return { success: true, count: mergedFiles.length };
  } catch (error) {
    console.error('缓存文件时出错:', error);
    throw error;
  }
};

// 发送缓存文件到后端生成审批表（DifyChangeController）
export const sendFilesToBackend = async (onProgress = null) => {
  const sessionId = getSessionId();
  const files = cachedFiles.get(sessionId);

  console.log('调用 sendFilesToBackend, sessionId:', sessionId)
  console.log('缓存文件:', files)

  if (!files || files.length < 2) {
    console.error('需要上传两个文件')
    throw new Error('需要上传两个文件：监督检查记录和责令整改通知书');
  }

  console.log('准备上传的缓存文件:', files);

  try {
    // DifyChangeController 需要 file1 和 file2 参数
    const formData = new FormData();
    formData.append('file1', files[0].file);
    formData.append('file2', files[1].file);

    const uploadUrl = `${API_CONFIG.baseUrl}/generation-shepibiao`;
    console.log('上传URL:', uploadUrl);
    console.log('上传文件数量:', files.length);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      body: formData
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('上传失败响应:', errorText);
      throw new Error(`文件上传失败: ${response.status} - ${errorText}`);
    }

    // DifyChangeController 现在返回 JSON 响应
    const result = await response.json();
    console.log('后端返回结果:', result);

    if (!result.success) {
      throw new Error(result.message || '生成审批表失败');
    }

    const data = result.data;

    // 清除缓存
    cachedFiles.delete(sessionId);
    console.log(`已成功上传并删除session ${sessionId}的缓存文件`);

    // 返回后端的完整数据，包括文件路径用于预览
    return {
      success: true,
      fileName: data.fileName,
      filePath: data.filePath,
      jsonData: data.jsonData,
      message: data.message || '审批表已生成'
    };
  } catch (error) {
    console.error('发送文件到后端时出错，保留缓存文件:', error);
    throw error;
  }
};

// 生成笔录 - 使用立案审批表的JSON数据（新接口）
export const generateInterrogationRecordFromJson = async (jsonData, sessionId = null) => {
  const actualSessionId = sessionId || getSessionId();

  console.log('调用 generateInterrogationRecordFromJson, sessionId:', actualSessionId)
  console.log('立案审批表JSON长度:', jsonData?.length)

  if (!jsonData) {
    console.error('没有提供立案审批表JSON数据')
    throw new Error('没有提供立案审批表JSON数据');
  }

  try {
    const uploadUrl = `${API_CONFIG.baseUrl}/generation-bilu`;
    console.log('笔录生成URL:', uploadUrl);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ jsonData })
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('笔录生成失败响应:', errorText);
      throw new Error(`笔录生成失败: ${response.status} - ${errorText}`);
    }

    // 现在返回 JSON 响应而不是文件流
    const result = await response.json();
    console.log('后端返回结果:', result);
    console.log('result.data详情:', result.data);  // 详细查看data内容

    if (!result.success) {
      throw new Error(result.message || '生成笔录失败');
    }

    const data = result.data;
    console.log('data.filePath:', data.filePath);  // 详细查看filePath

    // 返回完整的文件信息，包括文件路径用于预览
    return {
      success: true,
      fileName: data.fileName,
      filePath: data.filePath,
      message: data.message || '询问笔录已生成'
    };
  } catch (error) {
    console.error('生成笔录时出错:', error);
    throw error;
  }
};

// 下载文件（使用GeneratedFileController）
export const downloadFile = async (fileId, filename = 'document') => {
  try {
    const sessionId = getSessionId();

    const response = await fetch(`${API_CONFIG.generatedFileBaseUrl}/${fileId}`);

    if (!response.ok) {
      throw new Error(`下载文件失败: ${response.status}`);
    }

    // 创建下载链接
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();

    // 清理
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);

  } catch (error) {
    console.error('下载文件时出错:', error);
    throw error;
  }
};

// 获取文件历史列表（保留兼容性，但DifyChangeController不提供此功能）
export const getFileHistoryList = async () => {
  console.warn('DifyChangeController 不提供文件历史列表功能');
  return { files: [] };
};

// 获取单个文件历史（保留兼容性，但DifyChangeController不提供此功能）
export const getFileHistory = async (fileId) => {
  console.warn('DifyChangeController 不提供文件历史功能');
  return null;
};

// 下载Word文件
export const downloadWordFile = async (fileId, filename = 'document.docx') => {
  return downloadFile(fileId, filename);
};

// 填充案件表单（保留兼容性，但DifyChangeController不提供此功能）
export const fillCaseForm = async (jsonData, templateName) => {
  console.warn('DifyChangeController 不提供填充案件表单功能');
  throw new Error('此功能在当前接口中不可用');
};

// 生成行政处罚决定书 - 支持多文件上传
export const generatePenaltyDecision = async (caseApprovalFile, interrogationFile, evidenceFiles) => {
  console.log('调用 generatePenaltyDecision');
  console.log('立案审批表文件:', caseApprovalFile?.name);
  console.log('询问笔录文件:', interrogationFile?.name);
  console.log('证据文件数量:', evidenceFiles?.length);

  if (!caseApprovalFile) {
    throw new Error('必须上传立案审批表文件');
  }

  try {
    const formData = new FormData();
    formData.append('caseApprovalFile', caseApprovalFile);

    if (interrogationFile) {
      formData.append('interrogationFile', interrogationFile);
    }

    if (evidenceFiles && evidenceFiles.length > 0) {
      evidenceFiles.forEach(file => {
        formData.append('evidenceFiles', file);
      });
    }

    const uploadUrl = 'http://localhost:8018/api/penalty-decision/generate-from-file';
    console.log('上传URL:', uploadUrl);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      body: formData
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('生成处罚决定书失败响应:', errorText);
      throw new Error(`生成处罚决定书失败: ${response.status} - ${errorText}`);
    }

    const result = await response.json();
    console.log('后端返回结果:', result);

    if (!result.success) {
      throw new Error(result.message || '生成处罚决定书失败');
    }

    const data = result.data;

    return {
      success: true,
      fileName: data.fileName,
      filePath: data.filePath,
      jsonData: data.jsonData,
      evidenceFiles: data.evidenceFiles,
      lawBasis: data.lawBasis,
      punishmentAmount: data.punishmentAmount,
      message: data.message || '行政处罚决定书已生成'
    };
  } catch (error) {
    console.error('生成处罚决定书时出错:', error);
    throw error;
  }
};

// 生成行政处罚告知笔录（从文件上传）
export const generateAdminPunishmentNoticeFromFile = async (caseApprovalFile, interrogationFile, gaozhiType) => {
  console.log('调用 generateAdminPunishmentNoticeFromFile');
  console.log('立案审批表文件:', caseApprovalFile?.name);
  console.log('询问笔录文件:', interrogationFile?.name);
  console.log('告知类型:', gaozhiType);

  if (!caseApprovalFile) {
    throw new Error('必须上传立案审批表文件');
  }

  if (!interrogationFile) {
    throw new Error('必须上传询问笔录文件');
  }

  if (!gaozhiType) {
    throw new Error('没有选择告知类型');
  }

  if (gaozhiType !== '处罚前告知' && gaozhiType !== '听证告知') {
    throw new Error('告知类型必须是"处罚前告知"或"听证告知"');
  }

  try {
    const formData = new FormData();
    formData.append('caseApprovalFile', caseApprovalFile);
    formData.append('interrogationFile', interrogationFile);
    formData.append('gaozhiType', gaozhiType);

    const uploadUrl = `${API_CONFIG.baseUrl}/generation-gaozhi-from-file`;
    console.log('告知笔录生成URL（文件上传）:', uploadUrl);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      body: formData
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('告知笔录生成失败响应:', errorText);
      throw new Error(`告知笔录生成失败: ${response.status} - ${errorText}`);
    }

    const result = await response.json();
    console.log('后端返回结果:', result);

    if (!result.success) {
      throw new Error(result.message || '生成告知笔录失败');
    }

    const data = result.data;

    return {
      success: true,
      fileName: data.fileName,
      filePath: data.filePath,
      jsonData: data.jsonData,
      chaiLiangAdvice: data.chaiLiangAdvice,
      lawBasis: data.lawBasis,
      punishmentAmount: data.punishmentAmount,
      message: data.message || '行政处罚告知笔录已生成'
    };
  } catch (error) {
    console.error('生成告知笔录时出错:', error);
    throw error;
  }
};

// 生成行政处罚告知笔录（旧版本，使用JSON）
export const generateAdminPunishmentNotice = async (jsonData, gaozhiType, sessionId = null) => {
  const actualSessionId = sessionId || getSessionId();

  console.log('调用 generateAdminPunishmentNotice, sessionId:', actualSessionId);
  console.log('立案审批表JSON长度:', jsonData?.length);
  console.log('告知类型:', gaozhiType);

  if (!jsonData) {
    throw new Error('没有提供立案审批表JSON数据');
  }

  if (!gaozhiType) {
    throw new Error('没有选择告知类型');
  }

  if (gaozhiType !== '处罚前告知' && gaozhiType !== '听证告知') {
    throw new Error('告知类型必须是"处罚前告知"或"听证告知"');
  }

  try {
    const uploadUrl = `${API_CONFIG.baseUrl}/generation-gaozhi`;
    console.log('告知笔录生成URL:', uploadUrl);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ jsonData, gaozhiType })
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('告知笔录生成失败响应:', errorText);
      throw new Error(`告知笔录生成失败: ${response.status} - ${errorText}`);
    }

    const result = await response.json();
    console.log('后端返回结果:', result);

    if (!result.success) {
      throw new Error(result.message || '生成告知笔录失败');
    }

    const data = result.data;

    return {
      success: true,
      fileName: data.fileName,
      filePath: data.filePath,
      jsonData: data.jsonData,
      message: data.message || '行政处罚告知笔录已生成'
    };
  } catch (error) {
    console.error('生成告知笔录时出错:', error);
    throw error;
  }
};

